<template>
  <div class="choice-department">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="选择科室"
      left-arrow
      @click-left="goBack"
    />
    
    <!-- 院区切换 -->
    <van-tabs v-model:active="activeCampus" @change="handleCampusChange">
      <van-tab name="西院" title="西院" />
      <van-tab name="东院" title="东院" />
      <van-tab name="北院" title="北院" />
    </van-tabs>

    <!-- 科室列表 -->
    <div class="department-container">
      <!-- 一级科室列表 -->
      <div class="department-list primary-list">
        <div
          v-for="dept in departments"
          :key="dept.id"
          class="department-item"
          :class="{ active: selectedDept?.id === dept.id }"
          @click="selectDepartment(dept)"
        >
          {{ dept.name }}
        </div>
      </div>

      <!-- 二级科室列表 -->
      <div class="department-list secondary-list">
        <div
          v-for="child in selectedDept?.children || []"
          :key="child.id"
          class="department-item"
          @click="selectChildDepartment(child)"
        >
          {{ child.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { showToast } from 'vant'

const router = useRouter()
const activeCampus = ref('东院')
const departments = ref([])
const selectedDept = ref(null)

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取科室列表
const fetchDepartments = async (campus) => {
  try {
    const token = localStorage.getItem('token')
    const headers = { Authorization: token }
    const response = await axios.get(`http://127.0.0.1:8000/background/departments/${campus}/`, { headers })
    departments.value = response.data.departments
  } catch (error) {
    showToast('获取科室列表失败')
  }
}

// 切换院区
const handleCampusChange = (name) => {
  selectedDept.value = null
  fetchDepartments(name)
}

// 选择一级科室
const selectDepartment = (dept) => {
  selectedDept.value = dept
}

// 选择二级科室
const selectChildDepartment = (child) => {
  router.push({
    path: '/choice-doctor',
    query: {
      departmentId: child.id,
      departmentName: child.name
    }
  })
}

onMounted(() => {
  fetchDepartments(activeCampus.value)
})
</script>

<style scoped>
.choice-department {
  min-height: 100vh;
  background: #f5f5f5;
}

.department-container {
  display: flex;
  height: calc(100vh - 96px);
}

.department-list {
  overflow-y: auto;
  background: #fff;
}

.primary-list {
  width: 40%;
  border-right: 1px solid #eee;
}

.secondary-list {
  width: 60%;
}

.department-item {
  padding: 16px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
}

.department-item.active {
  color: #338bff;
  background: #f5f5f5;
}

/* 自定义 van-tabs 样式 */
:deep(.van-tabs__wrap) {
  border-bottom: 1px solid #eee;
}

:deep(.van-tab--active) {
  color: #338bff;
}

:deep(.van-tabs__line) {
  background-color: #338bff;
}
</style>